package com.nanbei.a12;



import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassDescription:  JDK 动态代理
 * @JdkVersion: 17
 * @Author: BaoShan.Li
 * @Date: 2024/11/17 21:10
 */
public class JdkProxyDemo {
    // 代理是兄弟的关系
    public static void main(String[] args) {
        Foo target = new Target();
        Foo o = (Foo)Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), new JdkProxy(target));
        o.foo();
    }
}

interface Foo{
    void foo();
    void fo2();
}

class Target implements Foo{

    @Override
    public void foo() {
        System.out.println("JDK proxy");
    }

    @Override
    public void fo2() {
        System.out.println("JDK proxy didi");
    }
}

// JDK 只针对接口代理
class JdkProxy implements InvocationHandler{

    private Object target;

    public JdkProxy(Object target) {
        this.target = target;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before");
        Object invoke = method.invoke(target, args);
        System.out.println("after");
        return invoke;
    }

}
